package cn.kgc.mushroomdatabaseprovider.usercontroller;

import cn.kgc.mushroomcommon.pojo.ResultEntity;
import cn.kgc.mushroomcommon.pojo.User;
import cn.kgc.mushroomcommon.util.CrowdConstant;
import cn.kgc.mushroomcommon.util.CrowdUtils;
import cn.kgc.mushroomdatabaseprovider.service.UserService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RequestMapping("/database/provider/user")
@RestController
public class UserController {
    @Resource
    UserService userService;

    @RequestMapping("/retrieve/user/by/login/acct")
    public ResultEntity<User> retrieveMemberByLoginAcct(@RequestParam("account") String account) {
        User user = null;
        try {
            user = userService.getUserByAccount(account);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed(e.getMessage());
        }
        return ResultEntity.successWithData(user);
    }

    @RequestMapping("/getUserByPhone")
    public ResultEntity<User> getUserByPhone(@RequestParam("phone") String phone) {
        User user = null;
        try {
            user = userService.getUserByPhone(phone);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed(e.getMessage());
        }
        return ResultEntity.successWithData(user);
    }

    @RequestMapping("/register")
    public ResultEntity<String> register(@RequestBody User user) {
        int i = userService.saveUser(user);
        if (i == 0) {
            return ResultEntity.failed("添加失败");
        }
        return ResultEntity.successNoData();
    }

    @RequestMapping("/retrieve/loign/acct/count")
    public ResultEntity<Integer> retrieveAccountCount(
            @RequestParam("account") String account) {
        if (!CrowdUtils.strEffectiveCheck(account)) {
            return ResultEntity.failed(CrowdConstant.MESSAGE_LOGINACCT_INVALID);
        }

        try {
            int count = userService.getAccountCount(account);

            return ResultEntity.successWithData(count);

        } catch (Exception e) {
            e.printStackTrace();

            return ResultEntity.failed(e.getMessage());
        }
    }

    @RequestMapping("/retrieve/loign/phone/count")
    public ResultEntity<Integer> getPhoneCount(
            @RequestParam("phone") String phone) {
        if (!CrowdUtils.strEffectiveCheck(phone)) {
            return ResultEntity.failed(CrowdConstant.MESSAGE_LOGINACCT_INVALID);
        }

        try {
            int count = userService.getPhoneCount(phone);

            return ResultEntity.successWithData(count);

        } catch (Exception e) {
            e.printStackTrace();

            return ResultEntity.failed(e.getMessage());
        }
    }
}
